package com.xilihui.xlh.business.fragments;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.facebook.drawee.view.SimpleDraweeView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.xilihui.xlh.R;
import com.xilihui.xlh.alipay.AuthResult;
import com.xilihui.xlh.alipay.PayResult;
import com.xilihui.xlh.business.activitys.ConfirmListingActivity;
import com.xilihui.xlh.business.activitys.MyChecklistActivity;
import com.xilihui.xlh.business.activitys.TakeGoodCodeActivity;
import com.xilihui.xlh.business.adapters.BasePagerAdapter;
import com.xilihui.xlh.business.dialogs.PatternDialog;
import com.xilihui.xlh.business.dialogs.PayDialog;
import com.xilihui.xlh.business.entities.AddOrderEntity;
import com.xilihui.xlh.business.entities.MyOrderEntity;
import com.xilihui.xlh.business.requests.MyAppointmentRequest;
import com.xilihui.xlh.component.recyclerview.BaseAdapter;
import com.xilihui.xlh.component.recyclerview.BaseViewHolder;
import com.xilihui.xlh.component.recyclerview.LinearLayoutColorDivider;
import com.xilihui.xlh.constant.StrConst;
import com.xilihui.xlh.constant.UrlConst;
import com.xilihui.xlh.core.app.BaseCompatFragment;
import com.xilihui.xlh.core.app.BaseEntity;
import com.xilihui.xlh.core.exception.DefaultExceptionListener;
import com.xilihui.xlh.core.exception.ExceptionManager;
import com.xilihui.xlh.core.http.DoTransform;
import com.xilihui.xlh.core.http.HttpSubscriber;
import com.xilihui.xlh.core.util.LogUtil;
import com.xilihui.xlh.core.util.SPUtil;
import com.xilihui.xlh.core.util.ToastUtil;
import com.xilihui.xlh.core.util.YEventBuses;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.Map;

import butterknife.BindView;

import static anet.channel.util.Utils.context;

/**
 * Created by Administrator on 2018/5/29.
 */

public class MyChecklistFragment extends BaseCompatFragment implements OnRefreshListener, OnLoadMoreListener, View.OnClickListener{

    @BindView(R.id.smartRefreshLayout)
    SmartRefreshLayout smartRefreshLayout;
    @BindView(R.id.recyclerview)
    RecyclerView recyclerView;
    
    ExceptionManager exceptionManager;
    
    ArrayList<MyOrderEntity.DeportOrderBean> datas = new ArrayList<>();
    BaseAdapter<MyOrderEntity.DeportOrderBean> beanBaseAdapter;
    
    String wa_id = "";
    String agent_id = ""; 
    String status = "10086";
    int page = 1;
    
    AddOrderEntity.PaymentParamsBean.WeixinBean weixinBean;
    
    String shopName = "";

    /** 支付宝支付业务：入参app_id */
    public static String orderInfo = "";
    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;
    
    Intent intent;

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        ToastUtil.toastShortPositive("支付成功");
                        YEventBuses.post(new YEventBuses.Event("yifukuang"));
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        ToastUtil.toastShortNegative("支付失败");
                    }
                    
                    break;
                }
                case SDK_AUTH_FLAG: {
                    @SuppressWarnings("unchecked")
                    AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
                    String resultStatus = authResult.getResultStatus();

                    // 判断resultStatus 为“9000”且result_code
                    // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
                    if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.getResultCode(), "200")) {
                        // 获取alipay_open_id，调支付时作为参数extern_token 的value
                        // 传入，则支付账户为该授权账户
                        ToastUtil.toastShortNegative("\"授权成功\\n\" + String.format(\"authCode:%s\", authResult.getAuthCode())");
                    } else {
                        // 其他状态值则为授权失败
                        ToastUtil.toastShortNegative("授权失败" + String.format("authCode:%s", authResult.getAuthCode()));
                    }
                    break;
                }
                default:
                    break;
            }
        };
    };
    
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_my_checklist,container,false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        YEventBuses.register(this);
        
        exceptionManager = new ExceptionManager(smartRefreshLayout,new DefaultExceptionListener(this)){
            @Override
            protected int getEmptyView() {
                return R.layout.empty_dingdan;
            }
        };
        
        smartRefreshLayout.setOnRefreshListener(this);
        smartRefreshLayout.setOnLoadMoreListener(this);
        
        recyclerView.addItemDecoration(new LinearLayoutColorDivider(getResources(),R.color.view_line,
                R.dimen.divider_space, LinearLayout.VERTICAL));
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        
        beanBaseAdapter = new BaseAdapter<MyOrderEntity.DeportOrderBean>(getActivity(),datas) {
            @Override
            protected int setLayoutId() {
                return R.layout.recycler_item_my_checklist;
            }
            
            @Override
            protected void getView(BaseViewHolder holder, MyOrderEntity.DeportOrderBean entity, int position) {
                
                holder.setText(R.id.tv_shopName,shopName);
                TextView textView = (TextView)holder.getView(R.id.tv_status);
                TextView tv_cancel = (TextView)holder.getView(R.id.tv_cancle);
                TextView tv_fukuang = (TextView)holder.getView(R.id.tv_fukuang);
                handleStatus(entity.getOrder_status(),textView,tv_cancel,tv_fukuang,entity.getOrder_id());
                holder.setText(R.id.tv_Price,"共"+entity.getGoods_num()+"件商品 合计￥"+entity.getGoods_price());
                
                RecyclerView recyclerViewe = (RecyclerView)holder.getView(R.id.recyclerview);
                recyclerViewe.addItemDecoration(new LinearLayoutColorDivider(getResources(),R.color.view_line,
                        R.dimen.divider_line,LinearLayout.VERTICAL));
                recyclerViewe.setLayoutManager(new LinearLayoutManager(getActivity()));
                ArrayList<MyOrderEntity.DeportOrderBean.DeportOrderGoodsBean> goodsBeans = 
                        (ArrayList<MyOrderEntity.DeportOrderBean.DeportOrderGoodsBean>) entity.getDeport_order_goods();
                
                BaseAdapter<MyOrderEntity.DeportOrderBean.DeportOrderGoodsBean> baseAdapter1 = 
                        new BaseAdapter<MyOrderEntity.DeportOrderBean.DeportOrderGoodsBean>(getActivity(),goodsBeans) {
                    @Override
                    protected int setLayoutId() {
                        return R.layout.recycler_item_shop_bill;
                    }
                    
                    @Override
                    protected void getView(BaseViewHolder holder, MyOrderEntity.DeportOrderBean.DeportOrderGoodsBean entity, int position) {
                        SimpleDraweeView simpleDraweeView = (SimpleDraweeView)holder.getView(R.id.iv_img);
                        simpleDraweeView.setImageURI(UrlConst.baseUrl()+entity.getOriginal_img());
                        
                        holder.setText(R.id.tv_name,entity.getGoods_name());
                        holder.setText(R.id.tv_model,entity.getSpec_key_name());
                        holder.setText(R.id.tv_num,"x"+entity.getGoods_num());
                        holder.setText(R.id.tv_price,"￥"+entity.getGoods_price());
                        
                    }
                };
                baseAdapter1.setAnimationsLocked(true);
                recyclerViewe.setAdapter(baseAdapter1);
            }
        };
        
        recyclerView.setAdapter(beanBaseAdapter);
        beanBaseAdapter.setAnimationsLocked(true);
        
        getExtras();
        getData(true);
        
    }

    private void getExtras() {
        wa_id = getArguments().getString("wa_id","");
        agent_id = getArguments().getString("agent_id","");
        int type = getArguments().getInt("status",0);
        switch (type){
            case 0:
                status = "10086";
                break;
            case 1:
                status = "0";
                break;
            case 2:
                status = "1";
                break;
            case 3:
                status = "2";
                break;
            case 4:
                status = "3";
                break;
        }
    }
    
    
    public void getData(boolean isLoading){
        MyAppointmentRequest.myOrder(getActivity(),wa_id,agent_id,status,page)
                            .compose(DoTransform.<MyOrderEntity>applyScheduler(getActivity(),isLoading))
                            .compose(this.<MyOrderEntity>bindToLifecycle())
                            .subscribe(new HttpSubscriber<MyOrderEntity>(getActivity()) {
                                @Override
                                protected void onSuccess(MyOrderEntity entity) {
                                    if(page ==1){
                                        datas.clear();
                                        if(entity.getDeport_order().size()<1){
                                            exceptionManager.showEmpty();
                                        }else {
                                            exceptionManager.hide();
                                        }
                                    }
                                    
                                    shopName = entity.getAgent_name();
                                    
                                    datas.addAll(entity.getDeport_order());
                                    beanBaseAdapter.setList(datas);

                                    smartRefreshLayout.finishRefresh();
                                    smartRefreshLayout.finishLoadMore();

                                    if(page>=entity.getPageCount()){
                                        smartRefreshLayout.finishLoadMoreWithNoMoreData();
                                    }else {
                                        smartRefreshLayout.setNoMoreData(false);
                                    }
                                    
                                }

                                @Override
                                protected void onFail(String msg) {
                                    smartRefreshLayout.finishRefresh();
                                    smartRefreshLayout.finishLoadMore();
                                    ToastUtil.toastShortNegative(msg);
                                }
                            });
        
    }
    
    public void handleStatus(String status, TextView textView, TextView tv_cancel, TextView tv_fukuang, final String id){
        
        if(status.equals("0")){
            textView.setText("待付款");
            tv_cancel.setVisibility(View.VISIBLE);
            tv_fukuang.setVisibility(View.VISIBLE);
            tv_cancel.setText("取消订单");
            tv_fukuang.setText("去付款");
            
            tv_cancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                    builder.setTitle("提示");
                    builder.setMessage("是否取消删除订单");
                    builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            MyAppointmentRequest.cancelOrder(getActivity(),id)
                                    .compose(DoTransform.<BaseEntity>applyScheduler(getActivity(),true))
                                    .subscribe(new HttpSubscriber<BaseEntity>(getActivity()) {
                                        @Override
                                        protected void onSuccess(BaseEntity entity) {
                                            ToastUtil.toastShortPositive(entity.getMsg());
                                            page = 1;
                                            getData(true);
                                        }

                                        @Override
                                        protected void onFail(String msg) {
                                            ToastUtil.toastShortNegative(msg);
                                        }
                                    });
                        }
                    });
                    builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {

                        }
                    });
                    builder.show();
                }
            });
            
            tv_fukuang.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                    builder.setMessage("请确认清单的商品门店库存充足");
                    builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {

                        }
                    });
                    builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            MyAppointmentRequest.myPay(getActivity(),id)
                                    .compose(DoTransform.<AddOrderEntity>applyScheduler(getActivity(),true))
                                    .subscribe(new HttpSubscriber<AddOrderEntity>(getActivity()) {
                                        @Override
                                        protected void onSuccess(AddOrderEntity entity) {

                                            orderInfo = entity.getPayment_params().getAlipay();
                                            weixinBean = entity.getPayment_params().getWeixin();
                                            PayDialog payDialog = new PayDialog(getActivity());
                                            payDialog.setOnItemSelectListener(new PayDialog.OnItemSelectListener() {
                                                @Override
                                                public void close() {

                                                }

                                                @Override
                                                public void alipay() {
                                                    payV2(recyclerView);
                                                }
                                                    
                                                @Override
                                                public void weixin() {
                                                    weixiPay();
                                                }
                                            });

                                            payDialog.show();

                                        }

                                        @Override
                                        protected void onFail(String msg) {
                                            ToastUtil.toastShortNegative(msg);
                                        }
                                    });
                        }
                    });

                    builder.show();
                    
                    
                }
            });
            
        }else if(status.equals("1")){
            textView.setText("待领货");
            tv_cancel.setVisibility(View.GONE);
            tv_fukuang.setVisibility(View.VISIBLE);
            tv_fukuang.setText("领货");
            
            tv_fukuang.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    intent = new Intent(getActivity(), TakeGoodCodeActivity.class);
                    intent.putExtra("id",id);
                    startActivity(intent);
                }
            });
            
        }else if(status.equals("2")){
            textView.setText("已领货");
            tv_cancel.setVisibility(View.GONE);
            tv_fukuang.setVisibility(View.GONE);
        }else if(status.equals("3")){
            textView.setText("已取消");
            tv_cancel.setVisibility(View.VISIBLE);
            tv_fukuang.setVisibility(View.GONE);
            tv_cancel.setText("删除");
            
            tv_cancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                    builder.setTitle("提示");
                    builder.setMessage("是否确认删除订单");
                    builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            MyAppointmentRequest.deleteOrder(getContext(),id)
                                    .compose(DoTransform.<BaseEntity>applyScheduler(getActivity(),true))
                                    .subscribe(new HttpSubscriber<BaseEntity>(getActivity()) {
                                        @Override
                                        protected void onSuccess(BaseEntity entity) {
                                            ToastUtil.toastShortNegative(entity.getMsg());
                                            page = 1;
                                            getData(true);
                                        }

                                        @Override
                                        protected void onFail(String msg) {
                                            ToastUtil.toastShortNegative(msg);
                                        }
                                    });
                        }
                    });
                    builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            
                        }
                    });
                    builder.show();
                }
            });
            
        }
    }


    /**
     * 支付宝支付业务
     *
     * @param v
     */
    public void payV2(View v) {
//        EnvUtils.setEnv(EnvUtils.EnvEnum.SANDBOX);


//        /**
//         * 这里只是为了方便直接向商户展示支付宝的整个支付流程；所以Demo中加签过程直接放在客户端完成；
//         * 真实App里，privateKey等数据严禁放在客户端，加签过程务必要放在服务端完成；
//         * 防止商户私密数据泄露，造成不必要的资金损失，及面临各种安全风险； 
//         *
//         * orderInfo的获取必须来自服务端；
//         */
//        boolean rsa2 = true;
//        Map<String, String> params = OrderInfoUtil2_0.buildOrderParamMap(APPID, rsa2);
//          
//        
//
//        String orderParam = OrderInfoUtil2_0.buildOrderParam(params);
//        final String orderInfo = orderParam + "&" + sign;

        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(getActivity());
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Log.i("msp", result.toString());
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        
        Thread payThread = new Thread(payRunnable);
        payThread.start();
        

    }

    public void weixiPay(){

        SPUtil.put(getActivity(),SPUtil.PAY_TYPE,1);
        IWXAPI msgApi = WXAPIFactory.createWXAPI(getActivity(),weixinBean.getAppid(), true);
        msgApi.registerApp(weixinBean.getAppid());

        boolean isWXAppInstalled = msgApi .isWXAppInstalled();
        if(isWXAppInstalled){
            PayReq request = new PayReq();
            request.appId = weixinBean.getAppid();
            request.partnerId = weixinBean.getPartnerid();
            request.prepayId= weixinBean.getPrepayid();
            request.packageValue = "Sign=WXPay";
            request.nonceStr= weixinBean.getNoncestr();
            request.timeStamp= weixinBean.getTimestamp();
            request.sign= weixinBean.getSign();
            msgApi.sendReq(request);
        }else {
            ToastUtil.toastShortPositive("请先安装微信");
        }

    }

  

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        page = 1;
        getData(false);
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        page = page + 1;
        getData(false);
    }
    

    @Subscribe
    public void onEventMainThread(YEventBuses.Event event) {
        if(event.is("yifukuang")){
            page  = 1;
            recyclerView.postDelayed(new Runnable() {
                @Override
                public void run() {
                    getData(false);
                }
            },2000);
        }else if(event.is(StrConst.UMENG_PUSH)){
            page = 1;
            getData(false);
        }
    }
            
    @Override
    public void onDestroy() {
        super.onDestroy();
        YEventBuses.unregister(this);
    }

    @Override
    public void onClick(View view) {
        
    }
}
